#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <windows.h>


int main()
{
    SOCKET s = INVALID_SOCKET;
    SOCKET remoteNode = INVALID_SOCKET;
    struct sockaddr_in remoteAddr = {0};

    WSADATA wsa = {0};

    if(WSAStartup(MAKEWORD(2, 2), &wsa))
    {
        printf("ERROR : can`t init winsock, status = %x\n", WSAGetLastError());
        return 0;
    }

    s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(INVALID_SOCKET == s)
    {
        printf("ERROR : can`t create local socket, status = %x\n", WSAGetLastError());
        WSACleanup();
        return 0;
    }

    struct sockaddr_in localAddr = {0};
    localAddr.sin_family = AF_INET;
    localAddr.sin_port = htons(31337);
    localAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(SOCKET_ERROR == bind(s, (struct sockaddr *)&localAddr, sizeof(localAddr)))
    {
        printf("ERROR : can`t bind local socket, status = %x\n", WSAGetLastError());
        closesocket(s);
        WSACleanup();
        return 0;
    }

    if(SOCKET_ERROR == listen(s, SOMAXCONN))
    {
        printf("ERROR : can`t set local socket to listen state, status = %x\n", WSAGetLastError());
        closesocket(s);
        WSACleanup();
        return 0;
    }

    int addrLen = sizeof(remoteAddr);
    while((remoteNode = accept(s, (struct sockaddr *)&remoteAddr, &addrLen)) != INVALID_SOCKET)
    {
        printf("new connection\n");
        closesocket(remoteNode);
    }

    printf("termination. %d\n", WSAGetLastError());

    if(s != INVALID_SOCKET)
        closesocket(s);

    WSACleanup();
    return 0;
}
